

// show loading spinner when load unfinished
$(window).on('load', function () {
	$('#loading-mask').fadeOut(200);
});



// ajax send form to server 
$('form').on('submit', function (event) {
	event.preventDefault();
	// set to valid as default
	var validity = true;

	// client side validation check
	'use strict'

	// Fetch all the forms we want to apply custom Bootstrap validation styles to
	var forms = document.querySelectorAll('.needs-validation')

	// Loop over them and prevent submission
	Array.prototype.slice.call(forms)
		.forEach(function (form) {
			form.classList.remove('was-validated');
			$('input').removeClass('is-invalid')
			if (!form.checkValidity()) {
				event.preventDefault()
				event.stopPropagation()
				validity = false;
			}
			// client-side check fail
			if (validity == false) {
				form.classList.add('was-validated');
			}
		});

	if (validity == true) {
		var url = $(this).attr("action");
		$.ajax({
			type: 'POST',
			url: url,
			data: $(this).serialize(),
			dataType: 'json',
			success: function (data) {
				if (data['info'] == "fail") {
					showInvalidation(data['message']);
				}
				else {
					$('form').addClass('was-validated');
					showAlert(data['message']);
					setTimeout(function () {
						window.location = data['url'];
					}, 1000);
				}
			},
			error: function (textStatus, thrownError) {
				console.log("Error: " + thrownError);
				console.log("Error: " + textStatus);
			}
		});
	}
});

// server-side validation repsonse
function showInvalidation(message) {
	// var forms = $('.card')
	if (message.includes("user")) {
		var feedback = $('#username-feedback');
		feedback.text(message);
		$('#client-username').hide();
		$('#username').addClass('is-invalid');
	}
	else if (message.includes('password')) {
		var feedback = $('#password-feedback');
		feedback.text(message);
		$('#client-password').hide();
		$('#password').addClass('is-invalid');
	}
}

// show alert when success
function showAlert(message) {
	let alert = $('.alert');
	alert.text(message);
	alert.toggle(300);
	setTimeout(function () {
		alert.toggle(300);
	}, 3000);
}